package com.wangshb.upms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wangshb.upms.core.constants.NumConstant;
import com.wangshb.upms.core.exception.OptimisticLockException;
import com.wangshb.upms.core.utils.AssertUtil;
import com.wangshb.upms.core.utils.Md5Util;
import com.wangshb.upms.entity.UpmsUser;
import com.wangshb.upms.mapper.UpmsUserMapper;
import com.wangshb.upms.service.UpmsUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import  com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;

@Service
@Slf4j
public class UpmsUserServiceImpl extends ServiceImpl<UpmsUserMapper, UpmsUser> implements UpmsUserService {

    @Resource
    private UpmsUserMapper upmsUserMapper;

    @Override
    public Page<UpmsUser> findPage(int pageNo, int pageSize, UpmsUser condition) {

        Page<UpmsUser> page = new Page<>(pageNo, pageSize, true);
        page.setRecords(findList(page, condition));
        return page;
    }

    @Override
    public List<UpmsUser> findList(Page<UpmsUser> page, UpmsUser condition) {
        return this.upmsUserMapper.findList(page, condition);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long addUpmsUser(UpmsUser upmsUser) {
        
        // 查看用户的登陆账号是否存在
        UpmsUser dbUpmsUser = this.findOne(UpmsUser.builder().userAccount(upmsUser.getUserAccount()).build());
        AssertUtil.isNull(dbUpmsUser, "登陆账号已经存在!");

        upmsUser.setPassword(Md5Util.MD5EncodeUtf8(upmsUser.getPassword(), upmsUser.getSalt()));
        this.upmsUserMapper.insert(upmsUser);
        return upmsUser.getId();
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delUpmsUser(UpmsUser upmsUser) {
        UpmsUser delEntity = new UpmsUser();
        delEntity.setId(upmsUser.getId());
        delEntity.setVersion(upmsUser.getVersion());
        delEntity.setDeleted(NumConstant.ONE);
        updateUpmsUserWithLock(delEntity);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateUpmsUserWithLock(UpmsUser upmsUser) {

        AssertUtil.notNull(upmsUser, "更新用户的数据不能为空");
        AssertUtil.notNull(upmsUser.getVersion(), "版本不能为空");

        // 修改时部分字段不允许修改
        upmsUser.setPassword(null);
        upmsUser.setUserAccount(null);

        if (!this.updateById(upmsUser)) {
            throw new OptimisticLockException("数据已被修改");
        }
    }

    @Override
    public UpmsUser findOne(UpmsUser upmsUser) {
        QueryWrapper<UpmsUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.setEntity(upmsUser);
        return this.upmsUserMapper.selectOne(queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void resetPassword(UpmsUser upmsUser) {
        UpmsUser dbUpmsUser = findOne(UpmsUser.builder().id(upmsUser.getId()).deleted(NumConstant.ZERO).valid(NumConstant.ONE).build());
        AssertUtil.notNull(dbUpmsUser, "用户不存在或已禁用，无法重置密码");

        UpmsUser updateUpmsUser = new UpmsUser();
        updateUpmsUser.setId(dbUpmsUser.getId());
        updateUpmsUser.setVersion(upmsUser.getVersion());
        updateUpmsUser.setPassword(Md5Util.MD5EncodeUtf8(updateUpmsUser.getPassword(), dbUpmsUser.getSalt()));
        if (!this.updateById(updateUpmsUser)) {
            throw new OptimisticLockException("数据已被修改");
        }
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchDelUpmsUser(List<Long> idList) {

        if (CollectionUtils.isEmpty(idList)) {
            log.info("删除用户失败，传入的用户主键为空.");
            return;
        }

        // 仅删除无效的用户数据
        UpdateWrapper<UpmsUser> updateWrapper = new UpdateWrapper<>();
        updateWrapper.in("id", idList).eq("valid", NumConstant.ZERO);
        int record = this.upmsUserMapper.update(UpmsUser.builder().deleted(NumConstant.ONE).build(), updateWrapper);
        log.warn("删除用户 - 共需要删除 {} 个用户, 其中成功删除 {} 个用户.", CollectionUtils.size(idList), record);
    }


    @Override
    public Set<String> findPermissions(String userAccount) {
        return this.upmsUserMapper.findPermissions(userAccount);
    }

    @Override
    public Set<String> findRoles(String userAccount) {
        return this.upmsUserMapper.findRoles(userAccount);
    }
}
